package cn.xiaopengstack.domain.trade.rule.trade;

import cn.xiaopengstack.domain.activity.model.entity.GroupBuyActivityEntity;
import cn.xiaopengstack.domain.activity.repository.IActivityRepository;
import cn.xiaopengstack.domain.trade.rule.factory.TradeRuleFilterFactory;
import cn.xiaopengstack.domain.trade.model.entity.TradeRuleCommandEntity;
import cn.xiaopengstack.domain.trade.model.entity.TradeRuleResponseEntity;
import cn.xiaopengstack.domain.trade.repository.ITradeRepository;
import cn.xiaopengstack.types.enums.ResponseCode;
import cn.xiaopengstack.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @author jiangyangang
 */
@Service
@Slf4j
public class TradeStockLockFilter extends AbstractTradeLogicLink<TradeRuleCommandEntity, TradeRuleFilterFactory.DynamicContext, TradeRuleResponseEntity>{

    public TradeStockLockFilter(ITradeRepository groupBuyOrderRepository, IActivityRepository activityRepository) {
        super(groupBuyOrderRepository, activityRepository);
    }

    @Override
    public TradeRuleResponseEntity apply(TradeRuleCommandEntity request, TradeRuleFilterFactory.DynamicContext dynamic) throws Exception {
        log.info("交易规则过滤-组队库存校验{} activityId:{}", request.getUserId(), request.getActivityId());

        // 首次组队不需要进行库存限制
        String teamId = request.getTeamId();
        GroupBuyActivityEntity groupBuyActivityEntity = dynamic.getGroupBuyActivityEntity();
        boolean occupyTeamStockResult = tradeRepository.occupyTeamStock(teamId, groupBuyActivityEntity.getActivityId(), (long) groupBuyActivityEntity.getTarget(), (long) groupBuyActivityEntity.getValidTime());
        if (!occupyTeamStockResult) {
            throw new AppException(ResponseCode.TRADE_OCCUPY_STOCK_FAIL);
        }

        return next(request, dynamic);
    }
}
